package com.me.websocket;

import java.net.InetSocketAddress;

import Server.Message;
import com.alibaba.fastjson.JSONObject;
import org.java_websocket.WebSocket;
import org.java_websocket.WebSocketImpl;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

public class WsServer extends WebSocketServer {
    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

    public WsServer(int port) {
        super(new InetSocketAddress(port));
    }

    public WsServer(InetSocketAddress address) {
        super(address);
    }

    // ws连接的时候触发的代码
    @Override
    public void onOpen(WebSocket conn, ClientHandshake handshake) {
        addOnlineCount();           //在线数加1
        System.out.println("New connection " + WsPool.getIpByWs(conn) + " on! People online is " + getOnlineCount() + "!");
    }

    // 断开连接时候触发代码
    @Override
    public void onClose(WebSocket conn, int code, String reason, boolean remote) {
        userLeave(conn);
        System.out.println(reason);
        subOnlineCount();           //在线数减1
        System.out.println("A connection off! People online is " + getOnlineCount() + "!");
    }

    // 收到消息时执行
    @Override
    public void onMessage(WebSocket conn, String message) {
        System.out.println("Message from " + WsPool.getIpByWs(conn) + " : " + message);
//        if (isJSONString(message)) {
        try {
            JSONObject jsonObject = JSONObject.parseObject(message);
            JSONObject res = Message.response(jsonObject, conn);
            if (null != res) {
                String response = res.toString();
                WsPool.sendMessageToUser(conn, response);
            }
        }
        catch (Exception e) {
            WsPool.sendMessageToUser(conn, "wrong type");
            System.out.println("wrong type");
        }
//        }
//        else {
//            WsPool.sendMessageToUser(conn, "wrong type");
//        }
//        if (null != message && message.startsWith("online")) {
//            String userName = message.replaceFirst("online", "");//用户名
//            userJoin(conn, userName);//用户加入
//        } else if (null != message && message.startsWith("offline")) {
//            userLeave(conn);
//        }
    }

    @Override
    public void onError(WebSocket conn, Exception ex) {
        //错误时候触发的代码
        System.out.println("on error!");
        ex.printStackTrace();
    }

    /**
     * 去除掉失效的websocket链接
     */
    private void userLeave(WebSocket conn) {
        String User = WsPool.getUserByWs(conn);
        if (User != null && Message.db.deleteRoom(User)) {
            System.out.println("IP " + WsPool.getIpByWs(conn) + " User " + User + " leave.");
        }
        else {
            System.out.println("IP " + WsPool.getIpByWs(conn) + " leave.");
        }
        WsPool.removeUser(conn);
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WsServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WsServer.onlineCount--;
    }

    // 判断是否为json格式字符串
    public static boolean isJSONString(String content) {
        if (null == content || content.length() == 0) {
            return false;
        }
        if (!content.startsWith("{") || !content.endsWith("}")) {
            return false;
        }
        try {
            JSONObject.parse(content);
            return true;
        }
        catch (Exception e) {
            return false;
        }
    }

    public static void main(String[] args) {
        WebSocketImpl.DEBUG = false;
        int port = 8887; // 端口
        WsServer s = new WsServer(port);
        s.start();
    }
}